<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.ticketName" placeholder="券名称" clearable style="width: 150px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        筛选
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="success" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      max-height="690"
      highlight-current-row
      style="width: 100%;"
      tooltip-effect="light"
      :default-sort="{prop: 'ticketId', order: null}"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" align="center" width="80" fixed prop="ticketId" sortable="custom">
        <template slot-scope="{row}">
          <span>{{ row.ticketId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="现金券名" align="center">
        <template slot-scope="{row}">
          <span>{{ row.ticketName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="简介" align="center" max-width="200px" show-overflow-tooltip>
        <template slot-scope="{row}">
          <span>{{ row.ticketDesc }}</span>
        </template>
      </el-table-column>
      <el-table-column label="抵扣价格" align="center" prop="ticketPrice" sortable="custom">
        <template slot-scope="{row}">
          <span>￥{{ roundPrice(row.ticketPrice) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="满减底价" align="center" prop="ticketCount" sortable="custom">
        <template slot-scope="{row}">
          <span v-if="row.ticketCount > 0">￥{{ roundPrice(row.ticketCount) }}</span>
          <el-tag v-else size="mini" effect="plain" type="info">无门槛</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="修改日期" align="center" prop="updateTime" sortable="custom">
        <template slot-scope="{row}">
          <span>{{ row.updateTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="260px" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="success" size="mini" @click="handleSend(row)">
            发放
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row.ticketId)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page-num.sync="listQuery.pageNum" :page-size.sync="listQuery.pageSize" @pagination="showTicketList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="35%">
      <el-form ref="dataForm" :rules="rules" :model="editTemp" label-width="100px" style="width: 80%; margin-left:50px;">
        <el-form-item label="消费券名" prop="ticketName">
          <el-input v-model="editTemp.ticketName" />
        </el-form-item>
        <el-form-item label="简介" prop="ticketDesc">
          <el-input v-model="editTemp.ticketDesc" />
        </el-form-item>
        <el-form-item label="抵扣价格" prop="ticketPrice">
          <el-input v-model="editTemp.ticketPrice" />
        </el-form-item>
        <el-form-item label="满减底价" prop="ticketCount">
          <el-input v-model="editTemp.ticketCount" placeholder="无门槛则填0" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="发放优惠券" :visible.sync="sendDialogVisible" width="40%" top="50px">
      <el-form ref="sendDirectForm" :rules="sendRules" :model="sendTemp" label-width="100px">
        <el-form-item label="发放对象">
          <el-radio v-model="sendRange" :label="1">全平台用户</el-radio>
          <el-radio v-model="sendRange" :label="2">选择用户</el-radio>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startDate">
              <el-date-picker v-model="sendTemp.startDate" type="date" placeholder="选择开始日期" format="yyyy-MM-dd HH:mm" value-format="yyyy-MM-dd HH:mm" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endDate">
              <el-date-picker v-model="sendTemp.endDate" type="date" placeholder="选择结束日期" format="yyyy-MM-dd HH:mm" value-format="yyyy-MM-dd HH:mm" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-transfer
          v-show="sendRange===2"
          v-model="transferUsersValue"
          v-loading="transferLoading"
          :data="transferUsersAll"
          filterable
          filter-placeholder="输入用户名搜索"
          :titles="['用户列表', '已选用户']"
          style="margin:15px 30px"
        />
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="sendDialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="doSend()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { showTicketList, deleteTicket, saveTicket, sendTicketDirect } from '@/api/ticket'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination'
import { isTwoDecimal, isTwoDecimalZero } from '@/utils/validate'
import { getUsersPlainList } from '@/api/users'
import { roundPrice } from '@/utils/common'

export default {
  name: 'Ticket',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      brandList: [],
      listQuery: {
        pageNum: 1,
        pageSize: 20,
        sortProp: '',
        sortOrder: '',
        ticketName: ''
      },
      editTemp: {
        ticketId: '',
        ticketName: '',
        ticketDesc: '',
        ticketPrice: '',
        ticketCount: ''
      },
      sendTemp: {
        ticketId: '',
        userListStr: '',
        startDate: '',
        endDate: ''
      },
      sendRange: 1,
      dialogFormVisible: false,
      sendDialogVisible: false,
      transferUsersAll: [],
      transferUsersValue: [],
      transferLoading: false,
      rules: {
        ticketName: [{ required: true, message: '请填写券名', trigger: 'blur' }],
        ticketDesc: [{ required: true, message: '请填写券简介', trigger: 'blur' }],
        ticketPrice: [{ required: true, message: '请填写抵扣价格', trigger: 'blur' }, { validator: isTwoDecimal, trigger: 'blur' }],
        ticketCount: [{ required: true, message: '请填写满减所需最低价格', trigger: 'blur' }, { validator: isTwoDecimalZero, trigger: 'blur' }]
      },
      sendRules: {
        startDate: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
        endDate: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
      },
      textMap: {
        update: '编辑',
        create: '新增'
      },
      dialogStatus: ''
    }
  },
  created() {
    this.showTicketList()
  },
  methods: {
    showTicketList() {
      this.listLoading = true
      showTicketList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 100)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.showTicketList()
    },
    sortChange(data) {
      const { prop, order } = data
      this.listQuery.sortProp = prop
      if (order === 'ascending') {
        this.listQuery.sortOrder = '1'
      } else {
        this.listQuery.sortOrder = '-1'
      }
      this.handleFilter()
    },
    resetDialog() {
      this.editTemp = {
        ticketId: '',
        ticketName: '',
        ticketDesc: '',
        ticketPrice: '',
        ticketCount: ''
      }
    },
    resetSendDialog() {
      this.sendTemp = {
        ticketId: undefined,
        userListStr: '',
        startDate: '',
        endDate: ''
      }
      this.sendRange = 1
    },
    handleCreate() {
      this.resetDialog()
      this.dialogFormVisible = true
      this.dialogStatus = 'create'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const data = Object.assign({}, this.editTemp)
          data.ticketPrice = data.ticketPrice * 100
          data.ticketCount = data.ticketCount * 100
          saveTicket(data).then(() => {
            this.showTicketList()
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '新增券成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.resetDialog()
      this.dialogStatus = 'update'
      this.editTemp = Object.assign({}, row)
      this.editTemp.ticketPrice = this.roundPrice(this.editTemp.ticketPrice)
      this.editTemp.ticketCount = this.roundPrice(this.editTemp.ticketCount)
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const data = Object.assign({}, this.editTemp)
          data.ticketPrice = data.ticketPrice * 100
          data.ticketCount = data.ticketCount * 100
          saveTicket(data).then(() => {
            this.showTicketList()
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '编辑券成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleSend(row) {
      this.resetSendDialog()
      this.sendTemp.ticketId = row.ticketId
      this.sendDialogVisible = true
      this.initTransfer()
      this.$nextTick(() => {
        this.$refs['sendDirectForm'].clearValidate()
      })
    },
    doSend() {
      this.$refs['sendDirectForm'].validate((valid) => {
        if (valid) {
          let userListStr = ''
          if (this.sendRange === 1) {
            userListStr = 0
          } else {
            this.transferUsersValue.forEach(value => {
              userListStr += value + ','
            })
            if (userListStr.length <= 0) {
              this.$message({
                message: '至少选择一名用户！',
                type: 'warning'
              })
              return
            }
          }
          sendTicketDirect({
            ticketId: this.sendTemp.ticketId,
            userListStr: userListStr,
            startDate: this.sendTemp.startDate,
            endDate: this.sendTemp.endDate
          }).then(response => {
            if (response.code === 0) {
              this.$notify({
                title: 'Success',
                message: '券已发放至用户账户！',
                type: 'success',
                duration: 2000
              })
              this.sendDialogVisible = false
              this.showTicketList()
            }
          })
        }
      })
    },
    initTransfer() {
      this.transferLoading = true
      this.transferUsersAll = []
      this.transferUsersValue = []
      getUsersPlainList(this.$store.getters.tmpDepartmentId).then(response => {
        const list = response.data
        for (let i = 0; i < list.length; i++) {
          this.transferUsersAll.push({
            key: list[i].userId,
            label: list[i].username
          })
        }
        setTimeout(() => {
          this.transferLoading = false
        }, 100)
      })
    },
    handleDelete(ticketId) {
      this.$confirm('此删除操作不可逆, 是否继续?', '提示', {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteTicket(ticketId).then(() => {
          this.showTicketList()
          this.dialogFormVisible = false
          this.$notify({
            title: 'Success',
            message: '删除券成功',
            type: 'success',
            duration: 2000
          })
        })
      })
    },
    roundPrice
  }
}
</script>

<style>
  .el-transfer-panel{
    width: 235px;
    height: 450px;
  }
  .el-transfer-panel__list.is-filterable{
    height: 400px;
  }
</style>
